<?php
/**
 * Fastapp.
 * 7/19/24
 * @Author deepsea
 * @Contact telegram:deepsea159 
 */

namespace App\Fastapp\Api\Service\Wechat;

use App\Fastapp\Api\Service\Account\AccountService;
use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Exception\TipException;
use App\Fastapp\Model\AccountOtherRelated;
use EasyWeChat\OfficialAccount\Application;

class MpService extends BaseService
{
    public function getRedirectUrl(array $data): array
    {
        $app = $this->app();
        $oauth = $app->getOAuth();
        $redirectUrl = $oauth->scopes([$data['scope'] ?? 'snsapi_base'])->redirect($app->getConfig()->get('oauth.redirect_url') . '/api/wechat/mp/redirectTo?r=' . $data['to_url']);
        return ['url' => $redirectUrl];
    }

    public function login(array $param): array
    {
        $app = $this->app();
        $client = $this->app()->getClient();

        $res = $client->get('/sns/oauth2/access_token', [
            'query' => [
                'grant_type' => 'authorization_code',
                'code' => $param['code'],
                'appid' => $app->getConfig()->get('app_id'),
                'secret' => $app->getConfig()->get('secret'),
            ]
        ]);
        $data = $res->toArray();
        if (empty($data['openid'])) throw new TipException(fastapp_t('account.login_failed'));
        $ur = AccountOtherRelated::query()->with(['account'])->firstOrCreate(['unique_code' => $data['openid'], 'related_type' => 1]);
        if ($ur->user_id) {
            $service = new AccountService();
            return $service->tokenFormat($ur->account);
        }
        if ($data['scope'] == 'snsapi_base') {
            return ['unique_code' => $data['openid'], 'type' => 1];
        }
        $res = file_get_contents('https://api.weixin.qq.com/sns/userinfo?' . http_build_query([
                'access_token' => $data['access_token'],
                'openid' => $data['openid'],
                'lang' => fastapp_lang(),
            ]));
        $res = json_decode($res, true);
        $d['unique_code'] = $res['openid'];
        $d['avatar'] = $res['headimgurl'];
        $d['nickname'] = $res['nickname'];
        $d['type'] = 1;
        return $d;
    }

    public function app(): Application
    {
        $config = api_cache()->getConfigByGroupKey('wechat');
        $config = [
            'app_id' => $config['mp_app_id'],
            'secret' => $config['mp_app_secret'],
            'aes_key' => $config['mp_aes_key'] ?? '',
            'token' => $config['mp_token'] ?? '',
            'oauth' => [
                'redirect_url' => $config['mp_app_domain'],
            ],
            'http' => [
                'throw' => true,
                'timeout' => 5.0,
                'retry' => true,
            ],
        ];
        $app = new Application($config);
        $app->setCache(container()->get(\Psr\SimpleCache\CacheInterface::class));
        return $app;
    }
}